<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p><i class="fa fa-list-alt"></i> 我的订单</p>
		</header>

		<!-- 未支付订单信息 -->
		<div class="section-container">
			<h3 class="section-title">
				<i class="fa fa-clock-o"></i>
				<span>未支付订单</span>
			</h3>
			<ul class="order-list">
				<li v-for="item in orderArr" :key="item.id" v-if="item.orderState === 0" class="order-card">
					<div class="order-header" @click="detailetShow(item)">
						<div class="order-header-left">
							<i class="fa fa-shopping-bag"></i>
							<span class="business-name">{{item.business.businessName}}</span>
						</div>
						<div class="order-header-right">
							<span class="order-total">¥{{item.orderTotal}}</span>
							<i class="fa fa-caret-down" :class="{ 'rotate': item.isShowDetailet }"></i>
						</div>
					</div>
					<div class="order-actions">
						<button class="action-btn pay-btn" @click="toPayment(item)">
							<i class="fa fa-credit-card"></i> 去支付
						</button>
						<button class="action-btn cancel-btn" @click="cancelOrder(item)">
							<i class="fa fa-times"></i> 取消订单
						</button>
					</div>
					<div class="order-details" v-show="item.isShowDetailet">
						<div class="detail-item" v-for="odItem in item.list" :key="odItem.id">
							<span class="detail-name">{{odItem.food.foodName}} x {{odItem.quantity}}</span>
							<span class="detail-price">¥{{(odItem.food.foodPrice * odItem.quantity).toFixed(2)}}</span>
						</div>
						<div class="detail-item delivery-fee">
							<span class="detail-name">配送费</span>
							<span class="detail-price">¥{{item.business.deliveryPrice}}</span>
						</div>
					</div>
				</li>
				<li v-if="orderArr.filter(item => item.orderState === 0).length === 0" class="empty-state">
					<i class="fa fa-inbox"></i>
					<p>暂无未支付订单</p>
				</li>
			</ul>
		</div>

		<!-- 配送中订单信息 -->
		<div class="section-container">
			<h3 class="section-title">
				<i class="fa fa-truck"></i>
				<span>配送中订单</span>
			</h3>
			<ul class="order-list">
				<li v-for="item in orderArr" :key="item.id" v-if="item.orderState === 1" class="order-card">
					<div class="order-header" @click="detailetShow(item)">
						<div class="order-header-left">
							<i class="fa fa-shopping-bag"></i>
							<span class="business-name">{{item.business.businessName}}</span>
						</div>
						<div class="order-header-right">
							<span class="order-total">¥{{item.orderTotal}}</span>
							<i class="fa fa-caret-down" :class="{ 'rotate': item.isShowDetailet }"></i>
						</div>
					</div>
					<div class="order-actions">
						<button class="action-btn delivered-btn" @click="confirmDelivered(item)">
							<i class="fa fa-check-circle"></i> 确认送达
						</button>
					</div>
					<div class="order-details" v-show="item.isShowDetailet">
						<div class="detail-item" v-for="odItem in item.list" :key="odItem.id">
							<span class="detail-name">{{odItem.food.foodName}} x {{odItem.quantity}}</span>
							<span class="detail-price">¥{{(odItem.food.foodPrice * odItem.quantity).toFixed(2)}}</span>
						</div>
						<div class="detail-item delivery-fee">
							<span class="detail-name">配送费</span>
							<span class="detail-price">¥{{item.business.deliveryPrice}}</span>
						</div>
					</div>
				</li>
				<li v-if="orderArr.filter(item => item.orderState === 1).length === 0" class="empty-state">
					<i class="fa fa-inbox"></i>
					<p>暂无配送中订单</p>
				</li>
			</ul>
		</div>

		<!-- 已送达订单信息 -->
		<div class="section-container">
			<h3 class="section-title">
				<i class="fa fa-check-circle"></i>
				<span>已送达订单</span>
			</h3>
			<ul class="order-list">
				<li v-for="item in orderArr" :key="item.id" v-if="item.orderState === 2" class="order-card">
					<div class="order-header" @click="detailetShow(item)">
						<div class="order-header-left">
							<i class="fa fa-shopping-bag"></i>
							<span class="business-name">{{item.business.businessName}}</span>
						</div>
						<div class="order-header-right">
							<span class="order-total">¥{{item.orderTotal}}</span>
							<i class="fa fa-caret-down" :class="{ 'rotate': item.isShowDetailet }"></i>
						</div>
					</div>
					<div class="order-details" v-show="item.isShowDetailet">
						<div class="detail-item" v-for="odItem in item.list" :key="odItem.id">
							<span class="detail-name">{{odItem.food.foodName}} x {{odItem.quantity}}</span>
							<span class="detail-price">¥{{(odItem.food.foodPrice * odItem.quantity).toFixed(2)}}</span>
						</div>
						<div class="detail-item delivery-fee">
							<span class="detail-name">配送费</span>
							<span class="detail-price">¥{{item.business.deliveryPrice}}</span>
						</div>
					</div>
				</li>
				<li v-if="orderArr.filter(item => item.orderState === 2).length === 0" class="empty-state">
					<i class="fa fa-inbox"></i>
					<p>暂无已送达订单</p>
				</li>
			</ul>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
	import Footer from '../components/Footer.vue';

	export default {
		name: 'OrderList',
		data() {
			return {
				orderArr: [],
				user: {}
			}
		},
		created() {
			const token = localStorage.getItem('id_token');
			if (!token) {
				this.$router.push('/login');
				return;
			}

			// 检查是否有支付成功提示
			if (this.$route.query.paymentSuccess === 'true') {
				const message = this.$route.query.message || '支付成功';
				alert(message);
				// 清除query参数，避免刷新页面时重复提示
				this.$router.replace({ path: '/orderList' });
			}

			// 获取订单列表（GET /api/orders/users）
			this.$axios.get('orders/users', {
				headers: {
					'Authorization': `Bearer ${token}`
				}
			}).then(response => {
				const result = response.data;
				if (result.success && result.code === 200) {
					// 给每个订单加"详情展开状态"字段
					this.orderArr = result.data.map(order => ({
						...order,
						isShowDetailet: false
					}));
				} else {
					alert('获取订单列表失败：' + (result.message || '未知错误'));
				}
			}).catch(error => {
				console.error('获取订单列表出错：', error);
			});
		},
		methods: {
			// 订单详情展开/收起
			detailetShow(orders) {
				orders.isShowDetailet = !orders.isShowDetailet;
			},
			// 去支付（跳转到支付页，保留原有逻辑）
			toPayment(order) {
				this.$router.push({
					path: '/payment',
					query: {
						orderId: order.id,
						totalAmount: order.orderTotal
					}
				});
			},
			// 新增：取消订单逻辑
			cancelOrder(order) {
				// 1. 防止误操作：让用户确认
				if (!confirm('确认取消该未支付订单吗？')) return;

				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				// 2. 发送PATCH请求：修改订单状态为-1（已取消）
				this.$axios.patch(`orders`, {
						id: order.id,
						orderState: -1
					}, // 请求体：传递要修改的状态
					{
						headers: {
							'Authorization': `Bearer ${token}`
						}
					}
				).then(response => {
					const result = response.data;
					// 3. 验证取消成功：后端返回orderState为-1
					if (result.data.orderState === -1) {
						alert('订单取消成功！');
						// 4. 前端实时更新：将该订单状态改为-1（不再显示在未支付列表）
						const targetOrder = this.orderArr.find(item => item.id === order.id);
						if (targetOrder) {
							targetOrder.orderState = -1;
						}
					} else {
						alert('取消订单失败：' + (result.message || '状态更新异常'));
					}
				}).catch(error => {
					console.error('取消订单出错：', error);
					alert('取消订单时发生错误，请稍后重试');
				});
			},
			// 新增：确认送达逻辑（调用钱包确认收货接口，解冻商家资金）
			confirmDelivered(order) {
				// 1. 防止误操作：让用户确认
				if (!confirm('确认该订单已送达吗？\n确认后，商家冻结的资金将解冻为可用余额。')) return;

				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				// 2. 调用钱包确认收货接口：POST /api/wallet/confirm-order
				this.$axios.post('wallet/confirm-order', null, {
					headers: {
						'Authorization': `Bearer ${token}`
					},
					params: {
						orderId: parseInt(order.id)
					},
					timeout: 10000
				}).then(response => {
					const result = response.data;
					// 3. 验证确认收货成功
					if (result.success && (result.code === 200 || result.code === 0)) {
						alert('订单已确认送达！商家冻结的资金已解冻为可用余额。');
						// 4. 前端实时更新：将该订单状态改为2（已送达）
						const targetOrder = this.orderArr.find(item => item.id === order.id);
						if (targetOrder) {
							targetOrder.orderState = 2;
						}
					} else {
						alert('确认送达失败：' + (result.message || '未知错误'));
					}
				}).catch(error => {
					let errorMsg = '确认送达时发生错误，请稍后重试';
					if (error.response && error.response.data) {
						const errorData = error.response.data;
						if (errorData.message) {
							errorMsg = errorData.message;
						}
					}
					alert(errorMsg);
				});
			},

		},
		components: {
			Footer
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		padding-bottom: 15vw;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		background-attachment: fixed;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
		font-size: 4.8vw;
		font-weight: 600;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		overflow: hidden;
	}

	.wrapper header::before {
		content: '';
		position: absolute;
		top: -50%;
		left: -50%;
		width: 200%;
		height: 200%;
		background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
		animation: pulse 3s ease-in-out infinite;
	}

	.wrapper header p {
		position: relative;
		z-index: 1;
		display: flex;
		align-items: center;
		gap: 2vw;
	}

	.wrapper header p i {
		font-size: 5vw;
	}

	@keyframes pulse {
		0%, 100% {
			transform: scale(1);
			opacity: 0.5;
		}
		50% {
			transform: scale(1.1);
			opacity: 0.8;
		}
	}

	/****************** 订单区块容器 ******************/
	.section-container {
		margin-top: 12vw;
		padding: 4vw;
		animation: slideDown 0.5s ease-out;
	}

	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-20px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.section-title {
		font-size: 4.5vw;
		font-weight: 600;
		color: #fff;
		margin-bottom: 3vw;
		display: flex;
		align-items: center;
		gap: 2vw;
		text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
	}

	.section-title i {
		font-size: 5vw;
		background: rgba(255, 255, 255, 0.2);
		padding: 2vw;
		border-radius: 50%;
		width: 9vw;
		height: 9vw;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/****************** 订单列表 ******************/
	.order-list {
		width: 100%;
		list-style: none;
		padding: 0;
		margin: 0;
	}

	.order-card {
		background: #fff;
		border-radius: 12px;
		margin-bottom: 3vw;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		overflow: hidden;
		transition: all 0.3s ease;
		animation: scaleIn 0.4s ease-out;
	}

	@keyframes scaleIn {
		from {
			opacity: 0;
			transform: scale(0.95);
		}
		to {
			opacity: 1;
			transform: scale(1);
		}
	}

	.order-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
	}

	.order-header {
		padding: 4vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		cursor: pointer;
		border-bottom: 1px solid #f0f0f0;
		transition: background-color 0.2s;
	}

	.order-header:hover {
		background-color: #f8f9fa;
	}

	.order-header-left {
		display: flex;
		align-items: center;
		gap: 2.5vw;
		flex: 1;
	}

	.order-header-left i {
		font-size: 5vw;
		color: #667eea;
	}

	.business-name {
		font-size: 4.2vw;
		font-weight: 600;
		color: #333;
	}

	.order-header-right {
		display: flex;
		align-items: center;
		gap: 3vw;
	}

	.order-total {
		font-size: 4.5vw;
		font-weight: 700;
		color: #ff6b6b;
	}

	.order-header-right i {
		font-size: 4vw;
		color: #999;
		transition: transform 0.3s ease;
	}

	.order-header-right i.rotate {
		transform: rotate(180deg);
	}

	/****************** 订单操作按钮 ******************/
	.order-actions {
		padding: 3vw 4vw;
		display: flex;
		gap: 2.5vw;
		justify-content: flex-end;
		border-top: 1px solid #f0f0f0;
	}

	.action-btn {
		padding: 2.5vw 5vw;
		border: none;
		border-radius: 8px;
		font-size: 3.5vw;
		font-weight: 600;
		cursor: pointer;
		display: flex;
		align-items: center;
		gap: 1.5vw;
		transition: all 0.3s ease;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.action-btn i {
		font-size: 3.5vw;
	}

	.action-btn:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
	}

	.action-btn:active {
		transform: translateY(0);
	}

	.pay-btn {
		background: linear-gradient(135deg, #ff9a56 0%, #ff6b6b 100%);
		color: #fff;
	}

	.pay-btn:hover {
		background: linear-gradient(135deg, #ff8a46 0%, #ff5b5b 100%);
	}

	.cancel-btn {
		background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
		color: #fff;
	}

	.cancel-btn:hover {
		background: linear-gradient(135deg, #e55c5c 0%, #d73c2c 100%);
	}

	.delivered-btn {
		background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
		color: #fff;
	}

	.delivered-btn:hover {
		background: linear-gradient(135deg, #42b40a 0%, #288e0d 100%);
	}

	/****************** 订单详情 ******************/
	.order-details {
		padding: 3vw 4vw;
		background: #f8f9fa;
		border-top: 1px solid #f0f0f0;
		animation: slideDown 0.3s ease-out;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 2.5vw 0;
		border-bottom: 1px solid #e9ecef;
	}

	.detail-item:last-child {
		border-bottom: none;
	}

	.detail-item.delivery-fee {
		border-top: 2px solid #dee2e6;
		margin-top: 2vw;
		padding-top: 3vw;
		font-weight: 600;
	}

	.detail-name {
		font-size: 3.8vw;
		color: #666;
	}

	.detail-price {
		font-size: 3.8vw;
		font-weight: 600;
		color: #333;
	}

	/****************** 空状态 ******************/
	.empty-state {
		background: #fff;
		border-radius: 12px;
		padding: 8vw 4vw;
		text-align: center;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	}

	.empty-state i {
		font-size: 12vw;
		color: #ddd;
		margin-bottom: 3vw;
	}

	.empty-state p {
		font-size: 3.8vw;
		color: #999;
		margin: 0;
	}
</style>